/*
 * rate2clk.c
 *
 *  Created on: 2022年1月28日
 *      Author: Rupert
 */

#include "rate2clk.h"
#include "math.h"

#define TIMER_CLK_FREQ_MHz (240)

static TimerCfgParamStructure timer_cfg = {
		.Prescaler = 23,
		.AutoReload = 999
};

TimerCfgParamStructure* rate2clk(uint32_t sample_rate)
{
	static float tmp = 0;
	if (sample_rate < 10)
	{
		timer_cfg.Prescaler = TIMER_CLK_FREQ_MHz * 100 - 1;
		tmp = 10000.0 / sample_rate;
		timer_cfg.AutoReload = (uint16_t)ceilf(tmp) - 1;
	}
	else if (sample_rate < 100)
	{
		timer_cfg.Prescaler = TIMER_CLK_FREQ_MHz * 10 - 1;
		tmp = 100000.0 / sample_rate;
		timer_cfg.AutoReload = (uint16_t)ceilf(tmp) - 1;
	}
	else if (sample_rate < 10000)
	{
		timer_cfg.Prescaler = TIMER_CLK_FREQ_MHz - 1;
		tmp = 1000000.0 / sample_rate;
		timer_cfg.AutoReload = (uint16_t)ceilf(tmp) - 1;
	}
	else if (sample_rate < 3600000)
	{
		timer_cfg.Prescaler = TIMER_CLK_FREQ_MHz / 10 - 1;
		tmp = 10000000.0 / sample_rate;
		timer_cfg.AutoReload = (uint16_t)ceilf(tmp) - 1;
	}
	else
	{
		timer_cfg.Prescaler = TIMER_CLK_FREQ_MHz / 10 - 1;
		tmp = 10000000.0 / 3600000;
		timer_cfg.AutoReload = (uint16_t)floorf(tmp) - 1;
	}
	return &timer_cfg;
}
